﻿using Common.Logger;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Common.Web
{
    /// <summary>
    /// httpClient诊断观察者
    /// </summary>
    public class HttpClientDiagnosticObserver : IObserver<KeyValuePair<string, object>>, IObserver<DiagnosticListener>
    {
        /// <summary>
        /// httpClient诊断观察者
        /// </summary>
        public void OnCompleted()
        {

        }
        /// <summary>
        /// 当发生错误时
        /// </summary>
        /// <param name="error"></param>
        public void OnError(Exception error)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        public void OnNext(KeyValuePair<string, object> value)
        {
            OnNext(value.Key, value.Value);
        }
        private void OnNext(string key, object value)
        {
            try
            {
                if (key == "System.Net.Http.HttpRequestOut.Stop")
                {
                    if (value == null)
                    {
                        return;
                    }
                    var valueType = value.GetType();
                    var request = valueType.GetProperty("Request")?.GetValue(value) as HttpRequestMessage;
                    if (request == null)
                    {
                        return;
                    }
                    var response = valueType.GetProperty("Response")?.GetValue(value) as HttpResponseMessage;
                    StringBuilder refit = new StringBuilder();
                    refit.Append($"{request.Method} {request.RequestUri}  ");
                    if (response != null)
                    {
                        refit.Append((int)response.StatusCode);
                        refit.Append(response.StatusCode);
                    }
                    else
                    {
                        refit.Append("unknown");
                    }
                    Log<HttpClientDiagnosticObserver>.Info(refit.ToString().TrimEnd());
                }
            }
            catch (Exception ex)
            {
                Log<HttpClientDiagnosticObserver>.Error("诊断日志出现异常", ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        public void OnNext(DiagnosticListener value)
        {
            if (value.Name == "HttpHandlerDiagnosticListener")
            {
                value.Subscribe(this);
            }
        }
    }
}
